<template>
	<view class="edit-book-container">
		<nav-bar :title="title" mode="user"></nav-bar>
		<view class="edit-body" v-if="bookDetail">
			<view class="edit-pagecount"><text>{{ currentPage + 1 }}</text>/{{ bookDetail.books_details_img.length }}
			</view>
			<view class="edit-swiper-box">
				<swiper class="edit-swiper" :autoplay="autoplay" :disable-touch="isPreivew" :interval="interval"
					:duration="duration" @change="handleChangePage" :acceleration="false" :current="currentPage">
					<swiper-item class="edit-swiper-item" v-for="(item, index) in bookDetail.books_details_img"
						:key="index">
						<view class="edit-swiper-item-box" style="width: 100%;">
							<!-- <view class="decals-wrap"> -->
							<decals v-if="!isPicked||index<bookDetail.books_details_img.length-1" ref="decalsRef"
								@matting="mattingFn" style="margin-top: 25px:width:100%;" :selectedFilePath="item.down_layer_all" :peopleImgType="item.peopleImgType"
								:editType="true" :peopleImg="item.people_img_all">
							</decals>
							<view v-else class="save-view">
								<image class="qr-bg" :src="cover_background" mode="widthFix"></image>
								<ayQrcode class="qr" ref="coverQrcode" qrcode_id="coverQrcode" :url="ayQrcodeUrl"
									:width="80" :height="80" @qrurl="qrurl" />
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<image src="../static/bc_hh.png" mode="widthFix" @click="handlePickThis()" class="edit-pick-btn"
				v-if="!isPicked"></image>
			<u-modal v-model="modalShow" :content="modalContent" :show-title="false" :show-cancel-button="true"
				@confirm="modalConfirm"></u-modal>
		</view>
		<!-- <view>编辑状态 {{ bookDetail.books_details_img[currentPage].isEdit }}</view> -->
		<view class="edit-tools-bar" v-if="isPicked&&!isPreivew&&bookDetail">
			<view v-if="currentPage<bookDetail.books_details_img.length-1" class="edit-tool" @click="chooseImage">
				<image src="../static/btn_icon2.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 照片 </view>
			</view>
			<view v-if="currentPage<bookDetail.books_details_img.length-1" class="edit-tool" @click="chooseMask">
				<image src="../static/btn_icon1.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 动图 </view>
			</view>
			<view v-if="currentPage<bookDetail.books_details_img.length-1" class="edit-tool" @click="showRecording">
				<image src="../static/btn_icon3.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 录音 </view>
			</view>
			<view v-if="currentPage<bookDetail.books_details_img.length-1" class="edit-tool" @click="save">
				<image src="../static/btn_icon4.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 保存 </view>
			</view>
			<view v-if="currentPage==bookDetail.books_details_img.length-1&& step ==1" @click="preview" class="edit-tool">
				<image src="../static/btn_icon1.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 预览 </view>
			</view>
			<view v-if="currentPage==bookDetail.books_details_img.length-1&& step ==2" class="edit-tool" @click="generateVideoFun">
				<image src="../static/img-new/stamp.png" mode="widthFix" class="edit-tool-img"></image>
				<view class="edit-tool-text"> 下载视频 </view>
			</view>
		</view>

		<!-- 动图 -->
		<mask-list :popupShow="popupShow" @popupClose="popupClose" @selectMask="selectMask" :itemlist="itemList"></mask-list>
		<!-- 录音 -->
		<Recording :url="record_url" :recordingShow="recordingShow" @closeRecording="closeRecording"
			@stop="stopRecording"></Recording>
		<!-- //照片裁剪 -->
		<l-clipper v-if="show==true" :image-url="imageUrl" @success="myUpload" @cancel="show = false" />
		<!-- 保存进入下一页 -->
		<u-modal v-model="saveModalShow" :content="saveModalContent" :show-cancel-button="true"
			@cancel="cancelSaveModal" @confirm="confirmSaveModal"></u-modal>
		<!-- 保存上一页 -->
		<u-modal v-model="saveModalShowPrev" content="是否保存上一页修改" :show-cancel-button="true"
			@cancel="cancelSaveModalPrev" @confirm="confirmSaveModalPrev"></u-modal>
		<!-- //合成封面 -->
		<canvas class="canvas-target-bg" id="canvas-target-bg" ref="canvasRef" :style="{
		        width: img_width + 'px',
		        height: img_height + 'px',
		        right: -(img_width + SCREEN_WIDTH) + 'px',
		    }" canvas-id="canvas-target-bg" style="position: fixed;top:-99999999px;"></canvas>
		<!-- 名字 -->
		<view class="u-flex" style="position: fixed;top:20rpx;right:20rpx;visibility: hidden;">
		    <view class="nameValueClass" style="font-size: 30px; -webkit-text-stroke: 1px white;">{{ nameValue }}的系列绘本</view>
		</view>
		<!-- 图片合成书册页 -->
		<view v-for="(item,idx) in len" :key="idx" style="position: fixed;top:-99999999px;" v-if="len">
			<synth :pictureBookArr="bookArr" ref="synthesRes" :synthIdx="idx" :len="len"></synth>
		</view>
		<!-- 封底合成 -->
		<backCover v-if="backCoverSrc" :img_url="backCoverSrc" style="position: fixed;top:-99999999px;" ref="coverRef" :backCoverSrc="qucallbackUrl"></backCover>
		<!-- 打印提示窗 -->
		<u-modal v-model="print_show" content="立即去打印" :show-cancel-button="true" confirm-text="前往打印" cancel-text="再看看" @confirm="printConfirm"></u-modal>
	</view>
</template>

<script>
	var innerAudioContext;
	const bgmAudioContext = uni.createInnerAudioContext();
	import NavBar from "components/NavBar";
	import decals from "components/decals/decals";
	import MaskList from "components/MaskList";
	import Recording from "components/Recording";
	import lClipper from "@/components/lime-clipper/index.vue";
	import ayQrcode from "@/components/ay-qrcode/ay-qrcode.vue";

	import synth from "@/components/decals/synthesis.vue";
	import backCover from "@/components/decals/backCover.vue";

	var self;
	const sysInfo = uni.getSystemInfoSync();
	const isIphoneX =
		sysInfo.model.search("iPhone X") !== -1 ||
		sysInfo.model.search("iPhone 11") !== -1;
	const paddingBottom = isIphoneX ? 30 : 0;
	const bottomNavHeight = 160;
	const toolbarHeight = 40;
	const SCREEN_WIDTH = sysInfo.windowWidth;
	const SCREEN_HEIGHT = sysInfo.windowHeight - bottomNavHeight - toolbarHeight - paddingBottom - 20;

	export default {
		components: {
			NavBar,
			decals,
			MaskList,
			Recording,
			lClipper,
			ayQrcode,
			synth,
			backCover
		},
		data() {
			return {
				//canvas
				canvasCtx: null, //背景和成名字字段
				SCREEN_WIDTH, // 图片容器宽度,
				SCREEN_HEIGHT,
				img_width: SCREEN_WIDTH,
				img_height: SCREEN_HEIGHT,

				//end
				title: "",
				bookId: null,
				isFree: null,
				modalShow: false,
				isPicked: false,
				modalContent: "",
				swiperData: {
					duration: 500,
				},
				// 当前swiper-item的索引
				currentPage: 0,
				prevPage: 0,
				selectedFilePath: "http://cartoon-books-static.ascetic.top/37ba49c7-835b-015c-61cc-b0bd1948e0e6.png",
				peopleImg: "",
				// 挂件列表是否显示
				popupShow: false,
				// 录音是否显示
				recordingShow: false,
				// 确认保存模态窗显示
				saveModalShow: false,
				saveModalContent: "保存并进入下一页",
				//裁剪
				show: false,
				imageUrl: null,
				deatilData: null,
				listItemid: '',
				bookDetail: null,
				imgurl: this.$url.baseImgUrl,
				//填图
				itemList: [],
				//文件夹id
				folder_id: null,
				//最后一页背景
				cover_background: '',
				//二维码
				qucallbackUrl:null,
				ayQrcodeUrl:'https://apps.dfabu.com/aUZO',
				coverQrcode: '',
				previewUrl: '',
				autoplay: false,
				record_url: null,
				isPreivew: false,
				interval: 1000,
				duration: 500,
				// 二次编辑
				edit: false,
				//名字
				nameValue:null,
				//名字信息
				bgInfo:null,
				//打印图片合成
				bookArr: null, //两张图合成书页字段
				len: 0,
				bookList: [],
				callbookList: [],
				//封底图
				backCoverUrl:null,
				backCoverSrc:null,
				//保存上一页
				saveModalShowPrev:false,
				//是否显示打印按钮
				step:1,//1显示预览 2显示打印
				//获取编辑数据
				editJson:null,
				print_show:false,
				//视频地址记录
				all_ffmpeg_path:null
			};
		},
		onLoad(option) {
			self = this
			this.listItemid = option.id
			this.folder_id = option.folder_id || null
			this.edit = option.edit || false
			if (this.edit) {
				this.isPicked = true
			}
			this.fetch();
		},
		onHide() {

		},
		methods: {
			//生成中
			generateVideoFun(){
				uni.downloadFile({
				    url: this.all_ffmpeg_path, //仅为示例，并非真实的资源
				    success: (res) => {
				        uni.saveVideoToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function (r) {
								uni.showToast({
									title:'下载成功,赶快去欣赏吧'
								})
							}
						});
				    }
				});
			},
			getEditJson(){
				this.$u.post("folder_books_details", {
					folder_id:this.folder_id
				}).then((res) => {
					this.editJson = res.data.img_info
					this.bookDetail.books_details_img.map((r,i)=>{
						r.peopleImgType = false
						let json = JSON.parse(res.data.img_info[i].reserve_data)
						r.reserve_data = json
						this.$refs.decalsRef[i].addMaskList = json
					})
				});
			},
			printConfirm(){
				this.print_show = false
				uni.switchTab({
					url:'/pages/chooseAddress'
				})
			},
			toPrint() {
				innerAudioContext = '';
				bgmAudioContext.stop();
				bgmAudioContext.destroy();
				this.$u.post('save_print_info',{
					folder_id:this.folder_id,
					print_info:JSON.stringify(this.callbookList)
				})
			},
			//二维码合成
			qrurl(e) {
				let _this = this
				uni.uploadFile({
					url: _this.$url.url + "upload_img",
					filePath: e,
					header: {
						Authorized: uni.getStorageSync('token')
					},
					name: "file",
					success: (uploadFileRes) => {
						if(uploadFileRes.statusCode=='200'){
							let res = JSON.parse(uploadFileRes.data);
							if(res.code == 1){
								let qrUrl = res.data.url
								_this.bookDetail.books_details_img[_this.bookDetail.books_details_img.length-1].qrCode = qrUrl
								_this.qucallbackUrl = qrUrl
								_this.backCoverComplete()
							}else{
								uni.showToast({
									title:res.msg,
									icon:'none'
								})
							}
						}else{
							uni.showToast({
								title:uploadFileRes.errMsg,
								icon:'none'
							})
						}
					},
				});
			},
			//封底图片
			backCoverComplete(){
				setTimeout(_=>{
					this.$refs.coverRef.save(res=>{
						this.bookDetail.books_details_img[this.bookDetail.books_details_img.length-1].compoundImgUrl = res
					})
				},0)
			},
			synthImg(i, callback) {
				this.$refs.synthesRes[i].save(sres => {
					this.bookList.push(sres)
					if (i < this.len - 1) {
						i++
						this.synthImg(i, callback)
					} else {
						callback && callback()
					}
				})
			},
			//俩图片合成一个页
			twoToOne() {
				let bookArr = this.$u.deepClone(this.bookDetail.books_details_img)
				bookArr.unshift({
					compoundImgUrl: this.bookDetail.books_img_all
				})
				bookArr = bookArr.reverse()
				switch (bookArr.length % 4) {
					case 1:
						bookArr.splice(1, 0, {
							compoundImgUrl: ''
						})
					break;
					case 2:
						bookArr.splice(1, 0, {
							compoundImgUrl: ''
						})
						bookArr.splice(bookArr.length-1, 0, {
							compoundImgUrl: ''
						})
					break;
					case 3:
						bookArr.splice(1, 0, {
							compoundImgUrl: ''
						})
					break;
				}
				this.bookArr = bookArr
				this.len = bookArr.length % 2 == 0 ? bookArr.length / 2 : (bookArr.length + 1) / 2
				this.bookList = []
				this.callbookList = []
				setTimeout(() => {
					this.synthImg(0, _ => {
						console.log(this.bookArr,'this.bookArr')
						let allarr = this.bookList.map((e,i)=>{
							return this.imgUpload(i)
						})
						Promise.all(allarr).then(res=>{
							console.log(this.callbookList, 'callbookList')
							this.toPrint();
							this.step = 2
						}).catch(res=>{
							this.step = 1
						})
					})
				},0)
			},
			imgUpload(idx, callback) {
				let that = this
				var promise = new Promise(function(resolve, reject){
				    uni.uploadFile({
				    	header: {
				    		Authorized: uni.getStorageSync('token')
				    	},
				    	url: that.$url.url + "upload_img",
				    	filePath: that.bookList[idx],
				    	name: "file",
				    	success: (uploadFileRes) => {
				    		let resu = JSON.parse(
				    			uploadFileRes.data
				    		);
				    		if (resu.code == 1) {
								that.callbookList[idx] = resu.data.url
								resolve(resu.data.url);
				    		}
				    	},
				    	fail(err) {
							reject(err);
				    		console.log(
				    			err,
				    			"err uploadFile"
				    		);
				    	},
				    });
				})
				return promise
			},
			fetch(id) {
				this.$u.post('books_details', {
					books_id: this.listItemid
				}).then(res => {
					res.data.books_img_all = this.$url.ali + res.data.books_img
					res.data.bg_audio = this.$url.ali + res.data.bg_audio
					res.data.books_details_img.map(r => {
						r.audio_all = this.$url.ali + r.audio
						r.down_layer_all = this.$url.ali + r.down_layer
						r.people_img_all = this.$url.ali + r.people_img
						r.related_images_all = r.related_images.map(x => {
							return this.$url.ali + x
						})
						r.compoundImgUrl = this.$url.ali + r.down_layer
						r.editType = true
						r.peopleImgType = true
					})
					this.backCoverSrc = this.$url.ali + res.data.cover_background
					this.cover_background = this.$url.ali + res.data.cover_background
					this.bookDetail = res.data
					this.record_url = this.bookDetail.books_details_img[0].audio_all || null
					this.itemList = this.bookDetail.books_details_img[this.currentPage].related_images_all
					bgmAudioContext.src = this.bookDetail.bg_audio
          this.modalSaveFn();
          if (this.edit) {
            this.init();
            bgmAudioContext.play();
						this.getEditJson();
					} else {
            this.audioFn();
          }
				})
			},
			//抠图
			mattingFn(localPath, fun) {
				this.$u
					.post("like_splitting", {
						image_url: localPath,
					})
					.then((res) => {
						fun(res.data.file_path);
					});
			},
			handlePickThis(id) {
				this.$u.post("select_user_books_type", {
					books_id: this.listItemid
				}).then((res) => {
					if (res.data.type == 2) {
						this.modalContent = "此本为免费绘本，确定要选用此本吗？";
						this.modalShow = true;
					} else if (res.data.type == 3) {
						this.modalContent = "确定选用此绘本，并在套餐配额中减去一本？";
						this.modalShow = true;
					} else if (res.data.type == 1) {
						this.modalContent = "确定选用此绘本？";
						this.modalShow = true;
					}
				});
			},
			// 点击选用此本
			modalConfirm() {
				this.$u.post('choose_books', {
					books_id: this.listItemid
				}).then(res => {
					this.folder_id = res.data.folder_id
					this.init()
					bgmAudioContext.play()
				})
			},
			// 加载 编辑用数据
			init() {
				this.currentPage = 0;
				setTimeout(() => {
					this.isPicked = true;
				}, 0);
				this.bookDetail.books_details_img.map((item, index, arr) => {
					item.isEdit = 0;
				});
				this.bookDetail.books_details_img.push({
					type: 'save',
					qrCode: '',//二维码
					down_layer_all:'',//背景图
					audio_all:'',//音乐
					isEdit:2,
				})
				setTimeout(e => {
					this.$refs.coverQrcode[0].crtQrCode();
				}, 500)
				this.audioFn();
			},
			handleChangePage(e) {
        console.log('this.bookDetail.books_details_img:', this.bookDetail.books_details_img)
				if (this.isPicked && this.currentPage < this.bookDetail.books_details_img.length) {
					this.audioFn();
					this.record_url = this.bookDetail.books_details_img[this.currentPage].audio_all
				}

				if(this.bookDetail.books_details_img[this.currentPage].type!='save'){
					this.itemList = this.bookDetail.books_details_img[this.currentPage].related_images_all
				}

				this.currentPage = e.detail.current;
				this.prevPage = this.currentPage == 0 ? 0 : this.currentPage - 1;
				if (this.isPreivew && this.currentPage == this.bookDetail.books_details_img.length - 1) {
					this.autoplay = false
					this.isPreivew = false
				}
				if (this.bookDetail.books_details_img[this.currentPage].isEdit == 1) {
					// 编辑状态为1：
					this.saveModalShowPrev = true;
				}
			},
			//裁剪
			myUpload(rsp) {
				let _this = this;
				_this.show = false;
				uni.uploadFile({
					header: {
						Authorized: uni.getStorageSync('token')
					},
					url: _this.$url.url + "upload_img",
					filePath: rsp.url,
					name: "file",
					success: (uploadFileRes) => {
						let res = JSON.parse(uploadFileRes.data);
						let mask = {
							url: res.data.url,
							tailorUrl: res.data.url,
							isPeople: true
						};
						_this.selectMask(mask, true);
					},
				});
			},
			chooseImage() {
				let _this = this;
				uni.chooseImage({
					count: 1,
					sizeType: ["original", "compressed"],
					sourceType: ["album", "camera"],
					success: function(res) {
						//启动上传等待中...
						uni.showLoading({
							title: '图片上传中',
						});
						uni.uploadFile({
							// #ifdef APP-PLUS
							url: _this.$url.url + "upload_file_oss",
							// #endif
							// #ifdef H5
							url: "api/upload_file_oss",
							// #endif
							filePath: res.tempFilePaths[0],
							header: {
								'Authorized': uni.getStorageSync('token')
							},
							success: (uploadFileRes) => {
                console.log(uploadFileRes)
								uni.hideLoading();
								if(uploadFileRes.statusCode == 200){
									let res = JSON.parse(uploadFileRes.data);
									if(res.code == 1){
										_this.imageUrl = res.data.url;
										_this.show = true;
									}
								}else{
									uni.showToast({
										title:uploadFileRes.errMsg,
										icon:'none'
									})
								}

							},
							fail: function(res) {
								uni.hideLoading();
								that.Tips({
									title: '上传图片失败'
								});
							}
						})
					}
				})
			},

			//预览绘本
			previewBook() {
				this.isPreivew = true
				this.currentPage = 0;
				this.autoplay = true;
				bgmAudioContext.play()
				bgmAudioContext.loop = true
				if (this.bookDetail.books_details_img[this.currentPage].audioTime) {
					this.interval = this.bookDetail.books_details_img[this.currentPage].audioTime * 1000;
				} else {
					this.interval = 10000;
				}
			},

			// 控制 maskList 是否显示
			chooseMask() {
				this.popupShow = true;
			},
			popupClose() {
				this.popupShow = false;
			},
			// 选择挂件
			selectMask(mask, isbg = true) {
				this.$refs.decalsRef[this.currentPage].selectMask(mask, isbg);
				this.changeEdit(1);
			},
			// 更改当前page的编辑状态
			changeEdit(state) {
				this.bookDetail.books_details_img[this.currentPage].isEdit = state;
			},
			// 控制 录音 是否显示
			showRecording() {
				this.recordingShow = true;
			},
			closeRecording() {
				this.recordingShow = false;
			},
			// 结束录音 获取录音文件地址
			stopRecording(e) {
				this.bookDetail.books_details_img[this.currentPage].audio_record = e.url
			},

			// 音频播放
			audioFn(fn) {

				if (this.bookDetail.books_details_img[this.currentPage].audio_all) {
					// #ifdef APP-PLUS
					innerAudioContext = plus.audio.createPlayer(this.bookDetail.books_details_img[this.currentPage].audio_all);
					innerAudioContext.setSessionCategory("ambient");
					innerAudioContext.play();
					this.bookDetail.books_details_img[self.currentPage].audioTime = innerAudioContext.getDuration();
					// #endif
				}
			},

			// 最后一页点击预览 自动回放 同时请求合成接口 获取视频
			preview() {
				this.twoToOne();
				this.previewBook()
				this.$u.http.setConfig({
					showLoading: false
				})

				if (this.edit) {
					// 二次编辑
					this.$u.post('in_folder_edit_book', {
						folder_id: this.folder_id,
						books_id: this.listItemid,
					}).then(res => {
						this.$u.http.setConfig({
							showLoading: true
						})
					})
				} else {
					this.$u.post('all_ffmpeg', {
						folder_id: this.folder_id,
						books_id: this.listItemid,
					}).then(res => {
						this.all_ffmpeg_path = res.data.video_url
						this.$u.http.setConfig({
							showLoading: true
						})
					})
				}

			},

			// 保存，跳到下一页
			save() {
				this.$u.http.setConfig({
					showLoading: false
				})
				this.saveModalShow = true;
				let mirroring = 0;
				let mask = this.$refs.decalsRef[this.currentPage].addMaskList.map(r => {
					if (
						r.size.width * r.scale.width < 0 &&
						r.size.height * r.scale.height >= 0
					) {
						mirroring = 1;
					}
					if (
						r.size.height * r.scale.height < 0 &&
						r.size.width * r.scale.width >= 0
					) {
						mirroring = 2;
					}
					if (
						r.size.width * r.scale.width < 0 &&
						r.size.height * r.scale.height < 0
					) {
						mirroring = 0;
						r.rotate = r.rotate + 180;
					}
					return {
						"src": r.url,
						"resize": {
							"width": Math.abs(r.size.width) * Math.abs(r.scale.width),
							"height": Math.abs(r.size.height) * Math.abs(r.scale.height)
						},
						"rotate": r.rotate,
						"location": {
							"x": r.center.x - (r.size.width * Math.abs(r.scale.width)) / 2,
							"y": r.center.y - (r.size.height * Math.abs(r.scale.height)) / 2
						},
						"mirroring": mirroring
					}
				})
				this.$refs.decalsRef[this.currentPage].save((r,i) => {
					let json_data = {
						"background": this.bookDetail.books_details_img[i].down_layer_all,
						"complete_background":r.url,
						"sub_image": [...mask],
						"audio": this.bookDetail.books_details_img[i].audio_all,
						"audio_time": this.bookDetail.books_details_img[i].audioTime?this.bookDetail.books_details_img[i].audioTime:10000,
						"width": this.$refs.decalsRef[i].img_width,
						"height": this.$refs.decalsRef[i].img_height,
						"name": uni.getStorageSync("user_info").nickname,
					}
					this.bookDetail.books_details_img[i].compoundImgUrl = r.url;
					this.$u.post('ffmpeg', {
						folder_id: this.folder_id,
						old_video_covers: this.bookDetail.books_details_img[i].down_layer_all,
						video_covers: r.url,
						reserve_data:JSON.stringify(this.$refs.decalsRef[i].addMaskList),
						json_data: JSON.stringify(json_data),
					}).then(res => {
						this.$u.http.setConfig({
							showLoading: true
						})
						if (i < this.bookDetail.books_details_img.length - 1) {
							this.changeEdit(2);
						}
					})
				},this.currentPage)
			},
			//保存上一页
			//确定
			confirmSaveModalPrev(){
				this.bookDetail.books_details_img[this.currentPage-1].isEdit = 2;
			},
			//取消
			cancelSaveModalPrev(){
				this.currentPage = this.currentPage - 1;
			},
			//end
			confirmSaveModal() {
				this.bookDetail.books_details_img[this.currentPage].isEdit = 2;
				this.prevPage = this.currentPage === 0 ? 0 : this.currentPage - 1;
				this.currentPage = this.currentPage + 1;
			},
			cancelSaveModal() {
				this.currentPage = this.currentPage - 1;
				this.prevPage = this.currentPage === 0 ? 0 : this.currentPage - 1;
				setTimeout((r) => {
					this.saveModalShow = false;
				}, 0);
			},
			// 名字加载
			modalSaveFn() {
			    let that = this;
				let name = uni.getStorageSync("user_info").nickname + "的系列绘本"
				this.nameValue = name
			    let info = uni.createSelectorQuery().select(".nameValueClass");
			    info.boundingClientRect(function (data) {
					that.bgInfo = data
					that.generateFn();
			    }).exec();
			},
			// 合成名字
			generateFn() {
				let that = this;
				let bgInfo = that.bgInfo ? that.bgInfo : {
						width: 0
					};
				let nameValue = this.nameValue
				this.canvasCtx = uni.createCanvasContext("canvas-target-bg", this);
				this.canvasCtx.clearRect(0, 0, this.img_width, this.img_height);
				uni.downloadFile({
					url: this.bookDetail.books_img_all,
					success: (res) => {
						if (res.statusCode === 200) {
							let path = res.tempFilePath;
							that.canvasCtx.drawImage(
								path,
								0,
								0,
								that.img_width,
								that.img_height
							);
							that.canvasCtx.font = "small-caps bold 20px/1 Handwritten"
							that.canvasCtx.setLineWidth(1)
							that.canvasCtx.fillText(
								nameValue,
								that.img_width - bgInfo.width - 10,
								40
							);
							that.canvasCtx.setStrokeStyle('black')
							that.canvasCtx.strokeText(nameValue, that.img_width - bgInfo.width - 10, 40)

							that.canvasCtx.draw(false, function() {
								uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: that.img_width,
										height: that.img_height,
										canvasId: "canvas-target-bg",
										success: function(res) {
											uni.uploadFile({
												url: that.$url.url + "upload_file_oss",
												filePath: res.tempFilePath,
												header: {
													Authorized: uni.getStorageSync('token')
												},
												name: "file",
												success: (uploadFileRes) => {
													let res = JSON.parse(
														uploadFileRes.data
													);
													if (res.code == 1) {
														that.bookDetail.books_img_all = res.data.url
													}
												},
												fail(err) {
													console.log(
														err,
														"err uploadFile"
													);
												},
											});
										},
										fail(e) {
											console.error(
												"canvasToTempFilePath",
												e
											);
										},
									},
									that
								);
							});
						}
					},
				});

			},
		},
	};
</script>

<style scoped>
	/* .edit-book-container{
		padding-bottom: 100px;
	} */
	html,
	body {
		height: 100%;
		position: relative;
	}

	.edit-body {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.edit-pagecount {
		margin-top: 40rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.edit-pagecount text {
		color: #92d14f;
	}

	.edit-swiper-box {
		margin-top: 40rpx;
		height: 1000rpx;
		width: 100%;
		/* margin-bottom:0px; */
	}

	.edit-swiper-item {
		width: 100%;
		box-sizing: border-box;
		padding: 0 80rpx;
	}

	.edit-swiper-item-box {
		/* background-color: red; */
		/* height: 100%; */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.save-view {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.save-view .qr-bg {
		width: 100%;
		height: 100%;
	}

	.save-view .qr {
		position: absolute;
		z-index: 2;
		width: 200rpx;
		top: 400rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.decals-wrap {
		width: 100rpx;
		height: 100rpx;
	}

	.edit-swiper {
		width: 100%;
		height: 100%;
	}

	.edit-pick-btn {
		/* margin-top: 80rpx;
		height: 80rpx;
		color: #fff;
		padding: 0 80rpx;
		background-color: #92d14f;
		border: 4rpx solid #fff;
		box-shadow: 0 0 10rpx #999;
		text-align: center;
		line-height: 80rpx;
		border-radius: 20rpx; */
		width: 50%;
		height: auto;
		display: inline-block;
		position: fixed;
		left: 25%;
		bottom: 30px;
	}

	.edit-tools-bar {
		width: 100%;
		height: 76px;
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: absolute;
		bottom: 0rpx;
		background-color: #33cc00;
		border-top-left-radius: 15px;
		border-top-right-radius: 15px;
	}

	.edit-tool {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: -16px;
	}

	.edit-tool-img {
		width: 100rpx;
		height: 100rpx;
		/* 	border-radius: 50%;
		background-color: red; */
	}

	.edit-tool-text {
		margin-top: 5px;
		color: #fff;
	}
</style>
